import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch, history } from 'umi';
import { isEmpty } from '@/utils/common';
import { Message } from '@/design';
import { queryOrderDetail } from '@/services/order';
import styles from './payment.less';

export default function (props:any) {

  let timed:any = undefined;
  const dispatch = useDispatch();
  const [orderInfo, setOrderInfo] = useState<any>({});

  const { payhold } = useSelector((state:any) => state.payment);
  const { orderNo = '' } = props.match.params;//查詢支付結果orderNo
  const { orderId } = props.location.query;


  const handleToPay = () => {
    if (!isEmpty(payhold.payUrl)) {
      document.location.href = payhold.payUrl;
    } else {
      // Toast.info('無有效支付信息' , 2, null, false);
      history.replace('/order');
    }
  }

  const checkPayState = () => {
    dispatch({
      type: 'payment/fetchPayResult',
      payload: payhold.lineOrderNo || orderNo,
      paymentback: () => {
        Message.error('訂單支付未完成，如確認已支付請稍後再試');
      },
      timed
    })
  }

  useEffect(() => {
    // handleToPay();
    timed = setInterval(() => {
      dispatch({
        type: 'payment/fetchPayResult',
        payload: payhold.lineOrderNo || orderNo,
        timed
      })
    }, 5000);
    dispatch({
      type: 'payment/fetchPayResult',
      payload: payhold.lineOrderNo || orderNo,
      timed
    })
    return () => {
      clearInterval(timed);
    }
  }, []);

  useEffect(() => {
    // handleToPay();
    fetchOrderDetail();
  }, []);

  const fetchOrderDetail = async () => {

    if (isEmpty(orderNo)) {
      history.replace('/order');
      return;
    };
    let result = await queryOrderDetail({ id: orderId, isReturnUmeIntegral: '1' });
    if (!result) return;
    setOrderInfo(result.data);
  }

  console.log('payhold', payhold)
  return <div className={styles.wait_wrap}>
    <div className={styles.bounce}>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </div>
    <div className={styles.info}>
      <div className={styles.order_amount}>NT$ {orderInfo.orderAmount}</div>
      <div className={styles.order_no}>訂單編號<br />{orderInfo.orderId}</div>
    </div>
    <div>
      <button className={`${styles.button} ${styles.pay}`} type="button" onClick={handleToPay}>立即支付</button>
      <button className={`${styles.button} ${styles.finish}`} type="button" onClick={checkPayState}>已完成支付</button>
    </div>
    <i className={styles.payment_logo}></i>
  </div>
}